


$.fn.simpleTree = function(opt){
   return this.each(function(){
    
		    var TREE = this;
		    var ROOT = $('.root',this);
		    var mousePressed = false;
		    var mouseMoved = false;
		    var dragMoveType = false;
		    var dragNode_destination = false;
		    var dragNode_source = false;
		    var dragDropTimer = false;
		    var ajaxCache = Array();
            var triggerAction = false
            var tempClass = ""
		    TREE.option = {
			    drag: true,
			    animate: false,
			    autoclose: false,
			    speed: 'medium',
			    afterMouseOut: true,
			    afterMouseOver: false,
			    textLink: 'Edit',
			    showLink:true,
			    afterAjax:false,
			    afterMove: 	false,
			    afterClick:	false,
			    afterDblClick:	false, 
			    // added by Erik Dohmen (2BinBusiness.nl) to make context menu cliks available
			    afterContextMenu:	false,
			    docToFolderConvert:false,
			    afterMouseOver:	true,
			    afterMouseOut:	true,
			    afterClickView:	true,
			    width: '300',
			    viewRoot:true,
			    eventInit:"default",
			    padding:20,
			    paddingRoot:0
		    };
		    TREE.option = $.extend(TREE.option,opt);
		    $.extend(this, {getSelected: function(){
			    return $('span.active', this).parent();
		    }});
		    TREE.closeNearby = function(obj)
		    {
    		    
			    $(obj).siblings().filter('.folder-open, .folder-open-last').each(function(){
				    var childUl = $('>ul',this);
				    var className = this.className;
				    this.className = className.replace('open','close');
				    if(TREE.option.animate)
				    {
					    childUl.animate({height:"toggle"},TREE.option.speed);
				    }else{
					    childUl.hide();
				    }
			    });
		    };
		    TREE.nodeToggle = function(obj)
		    {
		        triggerAction = true
			    var childUl = $('>ul',obj);
			    if(childUl.is(':visible')){
				    obj.className = obj.className.replace('open','close');

				    if(TREE.option.animate)
				    {
					    childUl.animate({height:"toggle"},TREE.option.speed);
				    }else{
					    childUl.hide();
				    }
			    }else{
				    obj.className = obj.className.replace('close','open');
				    if(TREE.option.animate)
				    {
					    childUl.animate({height:"toggle"},TREE.option.speed, function(){
						    if(TREE.option.autoclose)TREE.closeNearby(obj);
						    if(childUl.is('.ajax'))TREE.setAjaxNodes(childUl, obj.id);
					    });
				    }else{
					    childUl.show();
					    if(TREE.option.autoclose)TREE.closeNearby(obj);
					    if(childUl.is('.ajax'))TREE.setAjaxNodes(childUl, obj.id);
				    }
			    }
    			
    			
		    };
		    TREE.setTreeNodes = function(obj, useParent){
			    obj = useParent? obj.parent():obj;
			    $('li div > span', obj).addClass('text')
			    .bind('selectstart', function() {
				    return false;
    		
			    }).bind("contextmenu",function(){
				    $('.active',TREE).attr('class','text');
				    if(this.className=='text')
				    {
					    this.className='active';
				    }
				    if(typeof TREE.option.afterContextMenu == 'function')
				    {
					    TREE.option.afterContextMenu($(this).parent());
				    }
				    return false;
			    }).mousedown(function(event){
				    mousePressed = true;
				    cloneNode = $(this).parent().clone();
				    var LI = $(this).parent();
				    if(TREE.option.drag)
				    {
					    $('>ul', cloneNode).hide();
					    $('body').append('<div id="drag_container"><ul></ul></div>');
					    $('#drag_container').hide().css({opacity:'0.8'});
					    $('#drag_container >ul').append(cloneNode);
					    $("<img>").attr({id	: "tree_plus",src	: "images/plus.gif"}).css({width: "7px",display: "block",	position: "absolute",left	: "5px",top: "5px", display:'none'}).appendTo("body");
					    $(document).bind("mousemove", {LI:LI}, TREE.dragStart).bind("mouseup",TREE.dragEnd);
				    }
				    return false;
			    }).mouseup(function(){
				    if(mousePressed && mouseMoved && dragNode_source)
				    {
					    TREE.moveNodeToFolder($(this).parent());
				    }
				    TREE.eventDestroy();
			    });
    			
			    var lineName;
    	
    			
			    $('li', obj[0].parentNode).each(function(i){
    			            
			                if( TREE.option.viewRoot == false && this.className == "root"){
			                    return true; 
			                }
			                
			                
                            var className = this.className;
                            tempClass = className
                            var open = false;
                            var cloneNode=true;
                            var LI = this;
                            var childNode = $('>ul',this);
                            if(childNode.size()>0){
	                            var setClassName = 'folder-';
	                            if(className && className.indexOf('open')>=0){
		                            setClassName=setClassName+'open';
		                            open=true;
	                            }else{
		                            setClassName=setClassName+'close';
	                            }
	                            this.className = setClassName + ($(this).is(':last-child')? '-last':'');

	                            if(!open || className.indexOf('ajax')>=0)childNode.hide();
	                            TREE.setTrigger(this);
                            }else{
	                            var setClassName = 'doc';
	                            this.className = setClassName + ($(this).is(':last-child')? '-last':'');
    	                        
	                            $(this.childNodes[0]).prepend('<div style="float:left">&nbsp;</div><span class="folder-none">&nbsp;</span>')
    	                        if (TREE.option.showLink && tempClass != "root" ){
   	                          if (!$('span:last',this).hasClass("unselected")){
    	                              $('span:last',this).after('<a href="javascript:void(0)" style="display:none">'+TREE.option.textLink+'</a>')
	                              }
    	                        }
	                            
                         }

			    })

                var padding = 0
			    var initp = 0
			    var root = true
			    $('li', obj[0].parentNode).each(function(i){
                  if(TREE.option.viewRoot == false && root){
			         initp = 1
			         return true; 
			      }
			      padding = (parseInt(this.id.split("_")[0]) - initp) * TREE.option.padding//10 
                  if(TREE.option.paddingRoot > 0 ){
			         padding = padding + TREE.option.paddingRoot
			      }			      
			      $(this.childNodes[0].childNodes[0]).css('padding-left',padding + 'px');    
   		          //$(this.childNodes[0]).css('width',width + 'px');
			      root = false
			    })
    			
			    $('li > div', obj[0].parentNode)
			    .mouseover(function(){
				    if(typeof TREE.option.afterMouseOver == 'function')
				    {
					    TREE.option.afterMouseOver($(this).parent());
				    }
				    return false;
			    }).mouseout(function(){
				    if(typeof TREE.option.afterMouseOut == 'function')
				    {
					    TREE.option.afterMouseOut($(this).parent());
				    }
				    return false;
			    })
			    .dblclick(function(){
				    if(typeof TREE.option.afterDblClick == 'function')
				    {
					    TREE.option.afterDblClick($(this).parent());
				    }
				    return false;
				    // added by Erik Dohmen (2BinBusiness.nl) to make context menu actions
				    // available
			    }).click(function(){
				    /*$('.active',TREE).attr('class','text');*/
				    /*if(this.className=='text')
				    {
					    this.className='active';
				    }*/

				    if(typeof TREE.option.afterClick == 'function' && triggerAction == false)
				    {
					    TREE.option.afterClick($(this).parent());
				    }
				    TREE.nodeToggle($(this).parent().get(0));
                    //$(".activeDiv").removeClass("activeDiv");
                    ///$(this).addClass("activeDiv")
                    //var id = node[0].id.split("_")[1]
                    //fGetSelectedOrganigramHTML(id)
                
				    triggerAction = false
				    return false;
			    });
    			
    			
			    $('li > div > a', obj)
			    .click(function(){
				    if(typeof TREE.option.afterClickView == 'function')
				    {
					    TREE.option.afterClickView($(this).parent());
				    }
				    return false;
			    });
    			
    			
		    };
    		

		    TREE.setTrigger = function(node){
    			
			    $('>div',node).prepend('<div style="float:left">&nbsp;</div><div class="trigger"><span class="folder">&nbsp;</span></div>');
    			if (TREE.option.showLink && tempClass != "root" ){
    			    alert(tempClass)
    			    if (! $('span:last',$('>div',node)).hasClass("unselected")){
			            $('span:last',$('>div',node)).after('<a href="javascript:void(0)" style="display:none">'+TREE.option.textLink+'</a>')
                    }
    			}
			    
    		    var trigger = $('.trigger', node);
                trigger.click(function(event){
				    //TREE.nodeToggle(node);
			    });
		    };
    	
		    TREE.dragStart = function(event){
			    var LI = $(event.data.LI);
			    if(mousePressed)
			    {
				    mouseMoved = true;
				    if(dragDropTimer) clearTimeout(dragDropTimer);
				    if($('#drag_container:not(:visible)')){
					    $('#drag_container').show();
					    LI.prev('.line').hide();
					    dragNode_source = LI;
				    }
				    $('#drag_container').css({position:'absolute', "left" : (event.pageX + 5), "top": (event.pageY + 15) });
				    if(LI.is(':visible'))LI.hide();
				    var temp_move = false;
				    if(event.target.tagName.toLowerCase()=='span' && $.inArray(event.target.className, Array('text','active','trigger'))!= -1)
				    {
					    var parent = event.target.parentNode;
					    var offs = $(parent).offset({scroll:false});
					    var screenScroll = {x : (offs.left - 3),y : event.pageY - offs.top};
					    var isrc = $("#tree_plus").attr('src');
					    var ajaxChildSize = $('>ul.ajax',parent).size();
					    var ajaxChild = $('>ul.ajax',parent);
					    screenScroll.x += 19;
					    screenScroll.y = event.pageY - screenScroll.y + 5;

					    if(parent.className.indexOf('folder-close')>=0 && ajaxChildSize==0)
					    {
						    if(isrc.indexOf('minus')!=-1)$("#tree_plus").attr('src','images/plus.gif');
						    $("#tree_plus").css({"left": screenScroll.x, "top": screenScroll.y}).show();
						    dragDropTimer = setTimeout(function(){
							    parent.className = parent.className.replace('close','open');
							    $('>ul',parent).show();
						    }, 700);
					    }else if(parent.className.indexOf('folder')>=0 && ajaxChildSize==0){
						    if(isrc.indexOf('minus')!=-1)$("#tree_plus").attr('src','images/plus.gif');
						    $("#tree_plus").css({"left": screenScroll.x, "top": screenScroll.y}).show();
					    }else if(parent.className.indexOf('folder-close')>=0 && ajaxChildSize>0)
					    {
						    mouseMoved = false;
						    $("#tree_plus").attr('src','images/minus.gif');
						    $("#tree_plus").css({"left": screenScroll.x, "top": screenScroll.y}).show();

						    $('>ul',parent).show();
						    /*
							    Thanks for the idea of Erik Dohmen
						    */
						    TREE.setAjaxNodes(ajaxChild,parent.id, function(){
							    parent.className = parent.className.replace('close','open');
							    mouseMoved = true;
							    $("#tree_plus").attr('src','images/plus.gif');
							    $("#tree_plus").css({"left": screenScroll.x, "top": screenScroll.y}).show();
						    });

					    }else{
						    if(TREE.option.docToFolderConvert)
						    {
							    $("#tree_plus").css({"left": screenScroll.x, "top": screenScroll.y}).show();
						    }else{
							    $("#tree_plus").hide();
						    }
					    }
				    }else{
					    $("#tree_plus").hide();
				    }
				    return false;
			    }
			    return true;
		    };
		    TREE.dragEnd = function(){
			    if(dragDropTimer) clearTimeout(dragDropTimer);
			    TREE.eventDestroy();
		    };
		    TREE.setEventLine = function(obj){
			    obj.mouseover(function(){
				    if(this.className.indexOf('over')<0 && mousePressed && mouseMoved)
				    {
					    this.className = this.className.replace('line','line-over');
				    }
			    }).mouseout(function(){
				    if(this.className.indexOf('over')>=0)
				    {
					    this.className = this.className.replace('-over','');
				    }
			    }).mouseup(function(){
				    if(mousePressed && dragNode_source && mouseMoved)
				    {
					    dragNode_destination = $(this).parents('li:first');
					    TREE.moveNodeToLine(this);
					    TREE.eventDestroy();
				    }
			    });
		    };
		    TREE.checkNodeIsLast = function(node)
		    {
			    if(node.className.indexOf('last')>=0)
			    {
				    var prev_source = dragNode_source.prev().prev();
				    if(prev_source.size()>0)
				    {
					    prev_source[0].className+='-last';
				    }
				    node.className = node.className.replace('-last','');
			    }
		    };
		    TREE.checkLineIsLast = function(line)
		    {
			    if(line.className.indexOf('last')>=0)
			    {
				    var prev = $(line).prev();
				    if(prev.size()>0)
				    {
					    prev[0].className = prev[0].className.replace('-last','');
				    }
				    dragNode_source[0].className+='-last';
			    }
		    };
		    TREE.eventDestroy = function()
		    {
			    // added by Erik Dohmen (2BinBusiness.nl), the unbind mousemove TREE.dragStart action
			    // like this other mousemove actions binded through other actions ain't removed (use it myself
			    // to determine location for context menu)
			    $(document).unbind('mousemove',TREE.dragStart).unbind('mouseup').unbind('mousedown');
			    $('#drag_container, #tree_plus').remove();
			    if(dragNode_source)
			    {
				    $(dragNode_source).show().prev('.line').show();
			    }
			    dragNode_destination = dragNode_source = mousePressed = mouseMoved = false;
			    //ajaxCache = Array();
		    };
		   /* TREE.convertToFolder = function(node){
			    node[0].className = node[0].className.replace('doc','folder-open');
			    node.append('<ul><li class="line-last"></li></ul>');
			    TREE.setTrigger(node[0]);
			    TREE.setEventLine($('.line, .line-last', node));
		    };*/
		    TREE.convertToDoc = function(node){
			    $('>ul', node).remove();
			    $('img', node).remove();
			    node[0].className = node[0].className.replace(/folder-(open|close)/gi , 'doc');
		    };
		    TREE.moveNodeToFolder = function(node)
		    {
			    if(!TREE.option.docToFolderConvert && node[0].className.indexOf('doc')!=-1)
			    {
				    return true;
			    }else if(TREE.option.docToFolderConvert && node[0].className.indexOf('doc')!=-1){
				    TREE.convertToFolder(node);
			    }
			    TREE.checkNodeIsLast(dragNode_source[0]);
			    var lastLine = $('>ul >.line-last', node);
			    if(lastLine.size()>0)
			    {
				    TREE.moveNodeToLine(lastLine[0]);
			    }
		    };
		    TREE.moveNodeToLine = function(node){
			    TREE.checkNodeIsLast(dragNode_source[0]);
			    TREE.checkLineIsLast(node);
			    var parent = $(dragNode_source).parents('li:first');
			    var line = $(dragNode_source).prev('.line');
			    $(node).before(dragNode_source);
			    $(dragNode_source).before(line);
			    node.className = node.className.replace('-over','');
			    var nodeSize = $('>ul >li', parent).not('.line, .line-last').filter(':visible').size();
			    if(TREE.option.docToFolderConvert && nodeSize==0)
			    {
				    TREE.convertToDoc(parent);
			    }else if(nodeSize==0)
			    {
				    parent[0].className=parent[0].className.replace('open','close');
				    $('>ul',parent).hide();
			    }

			    // added by Erik Dohmen (2BinBusiness.nl) select node
			    if($('span:first',dragNode_source).attr('class')=='text')
			    {
				    $('.active',TREE).attr('class','text');
				    $('span:first',dragNode_source).attr('class','active');
			    }

			    if(typeof(TREE.option.afterMove) == 'function')
			    {
				    var pos = $(dragNode_source).prevAll(':not(.line)').size();
				    TREE.option.afterMove($(node).parents('li:first'), $(dragNode_source), pos);
			    }
		    };

		    TREE.addNode = function(id, text, callback)
		    {
			    var temp_node = $('<li><ul><li id="'+id+'"><span>'+text+'</span></li></ul></li>');
			    TREE.setTreeNodes(temp_node);
			    dragNode_destination = TREE.getSelected();
			    dragNode_source = $('.doc-last',temp_node);
			    TREE.moveNodeToFolder(dragNode_destination);
			    temp_node.remove();
			    if(typeof(callback) == 'function')
			    {
				    callback(dragNode_destination, dragNode_source);
			    }
		    };
		    TREE.delNode = function(callback)
		    {
			    dragNode_source = TREE.getSelected();
			    TREE.checkNodeIsLast(dragNode_source[0]);
			    dragNode_source.prev().remove();
			    dragNode_source.remove();
			    if(typeof(callback) == 'function')
			    {
				    callback(dragNode_destination);
			    }
		    };

		    TREE.init = function(obj)
		    {
			    TREE.setTreeNodes(obj, false);
			    //$.browser.msie &&
    			
			    //$(ROOT).append('<div><span>adad</span></div>');
    			
		        if( TREE.option.viewRoot == false)
		        {

			        $('div:first',ROOT[0]).remove();
			        $('ul:first',ROOT).css('display','block');
			        //ROOT.css('visibility','hidden');
			        if($.browser.msie){
			            $(ROOT).css('margin-top','-13px');
			        }
		        }
    			
		    };
           
           TREE.convertToFolder = function(obj){
               obj[0].className = "folder-open"
               $("span:first",obj).remove()
               $(obj[0].childNodes[0].childNodes[0]).after('<div class="trigger"><span class="folder">&nbsp;</span></div>')
               var trigger = $('.trigger', obj);
               trigger.click(function(event){
				   // TREE.nodeToggle(obj[0]);
			    });
               
           }
           
           TREE.convertToFolderNode = function(obj){
               obj[0].className = "doc"
               $(".trigger",obj[0].childNodes[0]).remove()
               $("ul:first",obj[0]).remove()
               $(obj[0].childNodes[0].childNodes[0]).after('<span class="folder-none">&nbsp;</span>')
           }

           TREE.calcultaPadding = function(objTree,obj){

                var padding = objTree[0].option.padding
                var paddingRoot = objTree[0].option.paddingRoot

                var parentInitial = parseInt(obj[0].parentNode.parentNode.id.split("_")[0])  
                padding = ((parentInitial + 1) * padding) + paddingRoot   
                $(obj[0].childNodes[0].childNodes[0]).css('padding-left',padding + 'px');
                var tempid=obj[0].id.split("_")[1]   
                obj[0].id = (parentInitial + 1) + "_" + tempid
                if(obj[0].childNodes.length > 1){
                    TREE.calcultaPaddingChild($(obj[0].childNodes[1]).children(),parentInitial  + 1 ,objTree[0].option.padding,objTree[0].option.paddingRoot)
                }
                   
                //TREE.calcultaPaddingChild(obj.childNodes[1].children())
           }            
           
           TREE.calcultaPaddingChild = function(obj,pos,padding,paddingRoot){
                if(obj.length == 0){ return false}
                var paddingLeft = ((pos + 1) * padding) + paddingRoot
                $(obj).each(function(i){
                    var tempid=this.id.split("_")[1]   
                    this.id = (pos + 1) + "_" + tempid
                    $(this.childNodes[0].childNodes[0]).css('padding-left',paddingLeft + 'px');
                    if(this.childNodes.length > 1){
                        TREE.calcultaPaddingChild($(this.childNodes[1]).children(),pos + 1,padding,paddingRoot)
                    }
                    
                })
           }          

           TREE.setTreeNodesFunction = function(obj){
	
			    $(obj)
			    .mouseover(function(){
				    if(typeof TREE.option.afterMouseOver == 'function')
				    {
					    TREE.option.afterMouseOver($(this).parent());
				    }
				    return false;
			    }).mouseout(function(){
				    if(typeof TREE.option.afterMouseOut == 'function')
				    {
					    TREE.option.afterMouseOut($(this).parent());
				    }
				    return false;
			    })
			    .dblclick(function(){
				    if(typeof TREE.option.afterDblClick == 'function')
				    {
					    TREE.option.afterDblClick($(this).parent());
				    }
				    return false;

			    }).click(function(){
				    if(typeof TREE.option.afterClick == 'function')
				    {
					    TREE.option.afterClick($(this).parent());
				    }
				    return false;
			    });
    			
			    $('a', obj)
			    .click(function(){
				    if(typeof TREE.option.afterClickView == 'function')
				    {
					    TREE.option.afterClickView($(this).parent());
				    }
				    return false;
			    });
    			
    			
		    };
           
        
           switch(TREE.option.eventInit){
	          case "default":
		        TREE.init(ROOT);
		        break;
            }
    		
	    });
    }
    
    var fnExtTree = {

        collapse : function(obj){
           $('ul',obj).hide();
           //$('ul:first',obj).show();
           $('li',obj).each(function(){
			        var className = this.className;
			        this.className = className.replace('open','close');
            });  
        
        },
        
        expandable : function(obj){
            $('ul',obj).show();
            $('li',obj).each(function(){
                var childUl = $('>ul',this);
                var className = this.className;
                this.className = className.replace('close','open');
            }); 
        },

        addNode : function(obj,node,text,id){
            
            var pos = (parseInt(node[0].id) + 1)
            var padding = obj[0].option.padding
            var paddingRoot = obj[0].option.paddingRoot
            var padding = ((parseInt(pos * padding)+paddingRoot) + "px" )
            var newid = pos + "_" + id
            html = '<li id="'+ newid + '" class="doc"><div><div style="float:left;padding-left:' + padding + '">&nbsp;</div><span class="folder-none">&nbsp;</span><span  class="text">' + text + '</span><a style="display:none;" href="javascript:void(0)">'+ obj[0].option.textLink +'</a></div></li>'            
            var convertFolder= false
            if(node[0].childNodes.length == 1){
                $(node[0]).append('<ul><ul>')
                convertFolder = true
            }
            
            $(node[0].childNodes[1]).prepend(html)
            var objActivateFn = $("div:first",node[0].childNodes[1]) 
            obj[0].setTreeNodesFunction(objActivateFn, false)
            
            if(convertFolder){
                obj[0].convertToFolder(node)
            }
            convertFolder=false
            
        },
        deletedNode : function(obj,node){
            var parentNode = node[0].parentNode.parentNode
            $(node).remove();
            var childNode = $('ul>li',parentNode)
            if(childNode.size() == 0){
            obj[0].convertToFolderNode($(parentNode))    
            }           
            
                        
        },
        
        updateNode : function(obj,node,parentNode,text){
            $("span:last",node[0].childNodes[0]).html(text);

            var convertFolder= false
            var convertFolderNone= false
            
            if(parentNode[0].childNodes.length == 1){
                $(parentNode[0]).append('<ul></ul>')
                convertFolder = true
            }
            if(convertFolder){
                obj[0].convertToFolder(parentNode)
            }

            convertFolder= false
            /*var childNode = $('li',node[0].parentNode.parentNode)
            var objParentOld = node[0].parentNode.parentNode*/
            var objParentOldID = node[0].parentNode.parentNode.id
   /*         if(childNode.size() == 1){
                convertFolderNone = true
            }  */
   
            $(parentNode[0].childNodes[1]).append(node[0])
   
            var objParentOld = $("#" + objParentOldID)
            if(objParentOld[0].childNodes.length > 1){
               if(objParentOld[0].childNodes[1].childNodes.length == 0){
                   obj[0].convertToFolderNode(objParentOld)    
               }
            }
   
   		    obj[0].calcultaPadding(obj,node)
		    
          /* var childNode = $('ul>li',node[0].parentNode.parentNode)
            if(childNode.size() == 1){
                obj[0].convertToFolderNode(node[0].parentNode.parentNode)    
            }    */
        },
        
        updateNodeOnlyText: function(node,text){
             $("span:last",node[0].childNodes[0]).html(text);
       
        }
        
        

    } 
    
  

   
    

//    
